import md5 from "md5-js/md5.js";
/**
 * 通过请求参数生成指纹
 * @param url 请求路径
 * @param params 请求参数
 * @param data 请求体
 * @returns Object
 */
const genSignalObj = (url, params, data)=>{
    // 解析url，只保留url的部分
    const path = new URL(url).pathname
    const queryString = new URLSearchParams(params).toString()
    let dataString = ''
    if (data instanceof FormData) {
        // TODO 处理 FormData
    } else if (typeof data === 'string') {
        dataString = data;
    } else {
        dataString = JSON.stringify(data); // 将对象转换为格式化的 JSON 字符串
    }
    const timestamp = new Date().getTime()
    const random = genRandomString(8)
    return {
        signal: md5(timestamp + random + path+"?"+queryString+dataString),
        timestamp: timestamp,
        random: random,
    }
}

/**
 * 获取指定长度的随机字符串
 */
const genRandomString = (length)=>{
    let result = ''
    const characters = '!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    const charactersLength = characters.length
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength))
    }
    return result
}

export {
    genSignalObj
}